package com.example.shiro.shiro.aspect;


import com.example.shiro.shiro.utils.SystemConsts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author chong
 * @create 2020/3/11
 * Desc:
 */

@Slf4j
@Component
public class MyHandlerInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RedisSessionDAO redisSessionDAO;
    @Autowired
    private SessionDAO sessionDAO;
    /**
     * 检查用户的浏览器版本是否为IE且版本号低于10.0
     *
     * @param request
     * @return true为兼容 false为版本过低不兼容
     */

    private boolean checkIE9orMore(HttpServletRequest request) {
        try {
            String header = request.getHeader("User-Agent");
            if (StringUtils.isNotBlank(header)) {
                header = header.toLowerCase();
                Pattern pattern = Pattern.compile("msie ([\\d.]+)");
                Matcher mat = pattern.matcher(header);
                if (mat.find()) {
                    Float version = Float.parseFloat(mat.group().split(" ")[1]);
                    return version >= 10f;
                } else {
                    return true;
                }
            }
        } catch (Exception e) {
            log.info("检测浏览器版本出错!" + e.getMessage());
        }
        return true;
    }


    /**
     * 拦截（Controller方法调用之前）
     *
     * @param request  request
     * @param response response
     * @param o        o
     * @return 通过与否
     * @throws Exception 异常处理
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object
            o) throws Exception {
        response.setHeader("X-XSS-Protection", "1; mode=block");
        String id = WebUtils.toHttp(request).getHeader("Authorization");
        Session session = sessionDAO.readSession(id);
        if(session.getAttribute(SystemConsts.OFF_LINE).toString() == "false"){
            return true;
        }else {
            SecurityUtils.getSubject().logout();
            response.sendRedirect("http://localhost:4203/loginIn");
            return false;
        }
    }

    // 此方法为处理请求之后调用（调用过controller方法之后，跳转视图之前）
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView) throws Exception {
        log.info("此方法为处理请求之后调用（调用过controller方法之后，跳转视图之前）");

    }

    // 此方法为整个请求结束之后进行调用
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {

    }
}

